NoPaste Service
DOWNLOAD
Language: C
Author: Matrix86
Description: [OpenGL] Cylinder Texture Sample
Date: 09/02/08 14:09
  1. /*
  2. ######################################################################
  3. #                                                                    #
  4. # Matrix86 Cylinder Texture Sample                                   #
  5. #                                                                    #
  6. # Copyright (C) 2008  Matrix86                                       #
  7. #                                                                    #
  8. # This program is free software; you can redistribute it and/or      #
  9. # modify it under the terms of the GNU General Public License        #
  10. # as published by the Free Software Foundation; either version 2     #
  11. # of the License, or (at your option) any later version.             #
  12. #                                                                    #
  13. # This program is distributed in the hope that it will be useful,    #
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of     #
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      #
  16. # GNU General Public License for more details.                       #
  17. #                                                                    #
  18. # http://www.gnu.org/copyleft/gpl.html                               #
  19. #                                                                    #
  20. # Linux: gcc -o textureSample textureSample.cpp -lGL -lglut          #
  21. ######################################################################
  22.  */
  23.  
  24. #include <iostream>
  25. #include <GL/glut.h>
  26. /* ascii codes for various special keys */
  27. #define ESCAPE 27
  28. #define PAGE_UP 73
  29. #define PAGE_DOWN 81
  30. #define UP_ARROW 72
  31. #define DOWN_ARROW 80
  32. #define LEFT_ARROW 75
  33. #define RIGHT_ARROW 77
  34.  
  35.  
  36. GLint FPS = 30;                         // Frame per Secondo. Vengono usati nella funzione di animazione
  37.                                         // per controllare il massimo numero di frame al secondo dell'animazione
  38.  
  39. GLfloat xrot=0;   // x rotation
  40. GLfloat yrot=0;   // y rotation
  41. GLfloat xspeed=0; // x rotation speed
  42. GLfloat yspeed=0; // y rotation speed
  43.  
  44. GLuint  texture[3];
  45. GLuint  filter;
  46. GLfloat z=-5.0f;
  47.  
  48. int spin_x = 0, old_x = 0;              // spin_ indica di quanto si deve ruotare la scena
  49. int spin_y = 0, old_y = 0;              // old_  indica la vecchia posizione del cursore
  50.  
  51. int fase = 0,old_fase=0;                // specifica lo stato dell' animazione
  52.  
  53. /* Struttura per l'immagine - contiene altezza, larghezza, e dati */
  54. struct Image {
  55.         unsigned long sizeX;
  56.         unsigned long sizeY;
  57.         char *data;
  58. };
  59. typedef struct Image Image;
  60.  
  61. /*
  62.  * processa l'azione selezionata dal menu
  63.  *
  64.  * op - intero che rappresenta l'azione selezionata nel menu
  65.  */
  66. void menu(int op) {
  67.  
  68.         switch(op) {
  69.                 case 'Q':
  70.                 case 'q':
  71.                         exit(0);
  72.         }
  73. }
  74.  
  75. /*
  76.  * invocata da GLUT quando un tasto viene premuto
  77.  *
  78.  * key - tasto premuto
  79.  * x, y - coordinate del cursore del mouse
  80.  */
  81. void keyboardDown(unsigned char key, int x, int y) {
  82.  
  83.         switch(key) {
  84.                 case 'Q':
  85.                 case 'q':
  86.                 case  27:   // ESC
  87.                         exit(0);
  88.                         break;
  89.                 case 'a':
  90.                        
  91.                         break;
  92.         }
  93. }
  94.  
  95. void specialKeyPressed(int key, int x, int y)
  96. {
  97.  
  98.         usleep(100);
  99.  
  100.         switch (key) {    
  101.                 case GLUT_KEY_PAGE_UP:
  102.                         z-=0.02f;
  103.                         break;
  104.    
  105.                 case GLUT_KEY_PAGE_DOWN:
  106.                         z+=0.02f;
  107.                         break;
  108.  
  109.                 case GLUT_KEY_UP:
  110.                         xspeed-=0.01f;
  111.                         break;
  112.  
  113.                 case GLUT_KEY_DOWN:
  114.                         xspeed+=0.01f;
  115.                         break;
  116.  
  117.                 case GLUT_KEY_LEFT:
  118.                         yspeed-=0.01f;
  119.                         break;
  120.  
  121.                 case GLUT_KEY_RIGHT:
  122.                         yspeed+=0.01f;
  123.                         break;
  124.  
  125.                 default:
  126.                         break;
  127.         }       
  128. }
  129.  
  130. /*
  131.  * invocata da GLUT quando un tasto viene rilasciato
  132.  *
  133.  * key - tasto premuto
  134.  * x, y - coordinate del cursore del mouse
  135.  */
  136. void keyboardUp(unsigned char key, int x, int y) {}
  137.  
  138. int ImageLoad(char *filename, Image *image) {
  139.         FILE *file;
  140.         unsigned long size;                 // Grandezza immagine in bytes
  141.         unsigned long i;
  142.         unsigned short int planes;          // Numero piani nell'immagine
  143.         unsigned short int bpp;             // Numero bits per pixel
  144.         char temp;
  145.  
  146.  
  147.         if ((file = fopen(filename, "rb"))==NULL)
  148.         {
  149.                 printf("File Not Found : %s\n",filename);
  150.                 return 0;
  151.         }
  152.  
  153.         fseek(file, 18, SEEK_CUR);
  154.  
  155.  
  156.         if ((i = fread(&image->sizeX, 4, 1, file)) != 1) {
  157.                 printf("Error reading width from %s.\n", filename);
  158.                 return 0;
  159.         }
  160.         printf("Width of %s: %lu\n", filename, image->sizeX);
  161.    
  162.  
  163.         if ((i = fread(&image->sizeY, 4, 1, file)) != 1) {
  164.                 printf("Error reading height from %s.\n", filename);
  165.                 return 0;
  166.         }
  167.         printf("Height of %s: %lu\n", filename, image->sizeY);
  168.    
  169.     // Calcola la grandezza (assumendo 24 bits o 3 bytes per pixel).
  170.         size = image->sizeX * image->sizeY * 3;
  171.  
  172.  
  173.         if ((fread(&planes, 2, 1, file)) != 1) {
  174.                 printf("Error reading planes from %s.\n", filename);
  175.                 return 0;
  176.         }
  177.         if (planes != 1) {
  178.                 printf("Planes from %s is not 1: %u\n", filename, planes);
  179.                 return 0;
  180.         }
  181.  
  182.  
  183.         if ((i = fread(&bpp, 2, 1, file)) != 1) {
  184.                 printf("Error reading bpp from %s.\n", filename);
  185.                 return 0;
  186.         }
  187.         if (bpp != 24) {
  188.                 printf("Bpp from %s is not 24: %u\n", filename, bpp);
  189.                 return 0;
  190.         }
  191.        
  192.  
  193.         fseek(file, 24, SEEK_CUR);
  194.  
  195.  
  196.         image->data = (char *) malloc(size);
  197.         if (image->data == NULL) {
  198.                 printf("Error allocating memory for color-corrected image data");
  199.                 return 0;       
  200.         }
  201.  
  202.         if ((i = fread(image->data, size, 1, file)) != 1) {
  203.                 printf("Error reading image data from %s.\n", filename);
  204.                 return 0;
  205.         }
  206.  
  207.         for (i=0;i<size;i+=3) {
  208.                 temp = image->data[i];
  209.                 image->data[i] = image->data[i+2];
  210.                 image->data[i+2] = temp;
  211.         }
  212.  
  213.  
  214.         return 1;
  215. }
  216.  
  217. // Load Bitmaps And Convert To Textures
  218. GLvoid LoadGLTextures(GLvoid) { 
  219.     // Load Texture
  220.         Image *image1;
  221.    
  222.     // allocate space for texture
  223.         image1 = (Image *) malloc(sizeof(Image));
  224.         if (image1 == NULL) {
  225.                 printf("Error allocating space for image");
  226.                 exit(0);
  227.         }
  228.  
  229.         if (!ImageLoad("img1.bmp", image1)) {
  230.                 exit(1);
  231.         }        
  232.  
  233.     // Create Textures 
  234.         glGenTextures(3, &texture[0]);
  235.  
  236.     // texture 1 (poor quality scaling)
  237.         glBindTexture(GL_TEXTURE_2D, texture[0]);   // 2d texture (x and y size)
  238.  
  239.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // cheap scaling when image bigger than texture
  240.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // cheap scaling when image smalled than texture
  241.  
  242.     // 2d texture, level of detail 0 (normal), 3 components (red, green, blue), x size from image, y size from image,
  243.     // border 0 (normal), rgb color data, unsigned byte data, and finally the data itself.
  244.         glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
  245.  
  246.     // texture 2 (linear scaling)
  247.         glBindTexture(GL_TEXTURE_2D, texture[1]);   // 2d texture (x and y size)
  248.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // scale linearly when image bigger than texture
  249.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // scale linearly when image smalled than texture
  250.         glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
  251.  
  252.     // texture 3 (mipmapped scaling)
  253.         glBindTexture(GL_TEXTURE_2D, texture[2]);   // 2d texture (x and y size)
  254.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // scale linearly when image bigger than texture
  255.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); // scale linearly + mipmap when image smalled than texture
  256.         glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
  257.  
  258.     // 2d texture, 3 colors, width, height, RGB in that order, byte data, and the data.
  259.         gluBuild2DMipmaps(GL_TEXTURE_2D, 3, image1->sizeX, image1->sizeY, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
  260. };
  261.  
  262. /*
  263.  * invocata quando la finestra cambia dimensione, oppure รจ occlusa da un'altra finestra
  264.  *
  265.  * width. height - dimensioni attuali della finestra
  266.  */
  267. void reshape(int width, int height)
  268. {
  269.         GLfloat fieldOfView = 45.0f;
  270.         glViewport (0, 0, (GLsizei) width, (GLsizei) height);
  271.  
  272.         glMatrixMode (GL_PROJECTION);
  273.         glLoadIdentity();
  274.         gluPerspective(fieldOfView, (GLfloat) width/(GLfloat) height, 0.1, 500.0);
  275.  
  276.         glMatrixMode(GL_MODELVIEW);
  277.         glLoadIdentity();
  278. }
  279.  
  280. /*
  281.  * disegna gli assi
  282.  *
  283.  * lenght - lunghezza degli assi
  284.  */
  285. void DrawAxes(float length)
  286. {
  287.         glPushMatrix();
  288.         glScalef(length, length, length);
  289.  
  290.         glLineWidth(2.f);
  291.         glBegin(GL_LINES);
  292.  
  293.                 // x red
  294.         glColor3f(1.f, 0.f, 0.f);
  295.         glVertex3f(0.f, 0.f, 0.f);
  296.         glVertex3f(1.f, 0.f, 0.f);
  297.  
  298.                 // y green
  299.         glColor3f(0.f, 1.f, 0.f);
  300.         glVertex3f(0.f, 0.f, 0.f);
  301.         glVertex3f(0.f, 1.f, 0.f);
  302.  
  303.                 // z blue
  304.         glColor3f(0.f, 0.f, 1.f);
  305.         glVertex3f(0.f, 0.f, 0.f);
  306.         glVertex3f(0.f, 0.f, 1.f);
  307.  
  308.         glEnd();
  309.         glLineWidth(1.f);
  310.  
  311.         glPopMatrix();
  312. }
  313.  
  314. void DisegnaCilindro(float raggio,float altezza){
  315.         glPushMatrix();
  316.         GLUquadricObj *quadObj;
  317.         quadObj = gluNewQuadric();
  318.         //gluQuadricDrawStyle(quadObj, GLU_FILL);
  319.         gluQuadricTexture(quadObj, GL_TRUE); // Cilindro texturizzato
  320.         gluQuadricNormals(quadObj, GLU_SMOOTH);
  321.         glRotatef(90,1,0,0);
  322.         glTranslatef(0,0,-0.5);
  323.         gluCylinder(quadObj, raggio, raggio, altezza, 20, 20);
  324.         glPopMatrix();
  325. }
  326.  
  327. /*
  328.  * disegna la scena
  329.  */
  330. void draw()
  331. {
  332.         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);             // Clear The Screen And The Depth Buffer
  333.         glLoadIdentity();                               // Reset The View
  334.  
  335.         glTranslatef(0.0f,0.0f,z);                  // move z units out from the screen.
  336.    
  337.         glRotatef(xrot,1.0f,0.0f,0.0f);         // Rotate On The X Axis
  338.         glRotatef(yrot,0.0f,1.0f,0.0f);         // Rotate On The Y Axis
  339.  
  340.         glBindTexture(GL_TEXTURE_2D, texture[filter]);   // choose the texture to use.
  341.  
  342.     //glBegin(GL_QUADS);                                // begin drawing a cube
  343.         DisegnaCilindro(1,3);
  344.     // Front Face (note that the texture's corners have to match the quad's corners)
  345.         glNormal3f( 0.0f, 0.0f, 1.0f);                              // front face points out of the screen on z.
  346.         glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);      // Bottom Left Of The Texture and Quad
  347.         glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);      // Bottom Right Of The Texture and Quad
  348.         glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);      // Top Right Of The Texture and Quad
  349.         glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);      // Top Left Of The Texture and Quad
  350.        
  351.         glEnd();                                    // done with the polygon.
  352.  
  353.         xrot+=xspeed;                           // X Axis Rotation     
  354.         yrot+=yspeed;                           // Y Axis Rotation
  355.  
  356.     // since this is double buffered, swap the buffers to display what just got drawn.
  357.         glutSwapBuffers();
  358. }
  359.  
  360. /*
  361.  * invocata ogni volta che non ci sono eventi pendenti da processare
  362.  */
  363. void idle() { }
  364.  
  365. /*
  366.  * inizializza lo stato di OpenGL
  367.  *
  368.  * width, height - larghezza e altezza della finestra OpenGL
  369.  */
  370. void initGL(int width, int height)
  371. {
  372.         LoadGLTextures();                           // load the textures.
  373.         glEnable(GL_TEXTURE_2D);                    // Enable texture mapping.
  374.         // colore e tipo delle luci     
  375.         GLfloat light_ambient_0[] =     {0.65, 0.65, 0.65, 1.0};// colore ambiente della luce 0
  376.         GLfloat light_diffuse_0[] = {1.0, 1.0, 1.0, 1.0};       // colore diffusione della luce 0
  377.         GLfloat light_specular_0[] = {1.0, 1.0, 1.0, 1.0};      // colore speculare della luce 0
  378.         GLfloat light_position_0[] = {5.0, 5.0, 0.0, 0.0};      // posizione della luce 0
  379.        
  380.         glLightfv (GL_LIGHT0, GL_AMBIENT,       light_ambient_0);
  381.         glLightfv (GL_LIGHT0, GL_DIFFUSE,       light_diffuse_0);
  382.         glLightfv (GL_LIGHT0, GL_SPECULAR,      light_specular_0);
  383.         glLightfv (GL_LIGHT0, GL_POSITION,      light_position_0);
  384.        
  385.         glEnable(GL_LIGHTING);
  386.         glEnable(GL_LIGHT0);
  387.        
  388.         glEnable(GL_COLOR_MATERIAL);
  389.         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  390.        
  391.         reshape(width, height);
  392.        
  393.         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  394.         glClearDepth(1.0f);
  395.        
  396.         glEnable(GL_DEPTH_TEST);
  397.         glDepthFunc(GL_LEQUAL);
  398. }
  399.  
  400.  
  401. int main(int argc, char** argv)
  402. {
  403.         int width = 800;
  404.         int eight = 600;
  405.        
  406.         glutInit(&argc, argv);
  407.        
  408.         glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
  409.         glutInitWindowSize(width, eight);
  410.         glutInitWindowPosition(100, 100);
  411.         glutCreateWindow("Cylinder Texture Example Matrix86");
  412.        
  413.         // registra le callback
  414.         glutKeyboardFunc(keyboardDown);
  415.         glutKeyboardUpFunc(keyboardUp);
  416.         glutSpecialFunc(&specialKeyPressed);
  417.         glutReshapeFunc(reshape);
  418.         glutDisplayFunc(draw);  
  419.         glutIdleFunc(draw);
  420.  
  421.         //glutTimerFunc((int) 1000/FPS, animation, 0);
  422.         glutIgnoreKeyRepeat(false); // process keys held down
  423.                
  424.         // crea il menu principale (apribile con click destro)
  425.         glutCreateMenu(menu);
  426.         //glutAddMenuEntry("Start/Stop", 'a');
  427.         glutAddMenuEntry("Quit", 'q');
  428.         glutAttachMenu(GLUT_RIGHT_BUTTON);
  429.        
  430.         // inizializza lo stato di OpenGL
  431.         initGL(width, eight);
  432.        
  433.         // entra nel rendering loop     
  434.         glutMainLoop();
  435.         return 0;
  436. }
  437.  
  438.